package team.seekers.hula.question.answer.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import team.seekers.hula.question.answer.mapper.AnswerGoodMapper;
import team.seekers.hula.question.answer.entity.dao.AnswerGoodDO;
import team.seekers.hula.auth.service.MindUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户给一个回答点赞 服务实现类
 * </p>
 *
 * @author hbc
 * @since 2021-02-18
 */
@Service
public class AnswerGoodService extends ServiceImpl<AnswerGoodMapper, AnswerGoodDO> {

    private boolean result;

    @Autowired
    private AnswerService answerService;

    public void changeGood(String answerId,String userId) {
        if(hasGood(answerId,userId)){
            // 维护评论赞数
            answerService.reduceGood(answerId);

            // 删除赞
            QueryWrapper<AnswerGoodDO> wrapper = new QueryWrapper<>();
            wrapper.eq("answer_id", answerId);
            remove(wrapper);
        }else {
            // 维护评论赞数
            answerService.addGood(answerId);

            // 新增赞
            AnswerGoodDO answerGoodDO = new AnswerGoodDO();
            answerGoodDO.setAnswerId(answerId);
            answerGoodDO.setUserId(MindUtils.getUserId());
            save(answerGoodDO);
        }
    }

    //判断是否已经点过赞了，true为已经点过了
    public boolean hasGood(String answerId,String userId){
        QueryWrapper<AnswerGoodDO> wrapper = new QueryWrapper<>();
        wrapper.eq("answer_id", answerId);
        wrapper.eq("user_id", userId);
        AnswerGoodDO answerGoodDO = getOne(wrapper);
        if(answerGoodDO == null){
            return false;
        }else {
            return true;
        }
    }

    public void deleteByAnswerId(String answerId) {
        QueryWrapper<AnswerGoodDO> wrapper = new QueryWrapper<>();
        wrapper.eq("answer_id",answerId);
        remove(wrapper);
    }

}
